package handlers

import (
	"net/http"

	"gitee.com/anxu/golang-web/src/service"
)

type Auth struct {
	hander
}

func (this *Auth) Login(w http.ResponseWriter, r *http.Request) {
	if user := this.user(); user != nil {
		this.redirect("/", http.StatusFound, w, r)
		return
	}

	if r.Method == http.MethodPost {
		username := r.FormValue("email")
		password := r.FormValue("password")
		if username != "" && password != "" && service.User.LoginByPassword(username, password, w, r) {
			service.Logger.Info("用户" + username + "登录..")
			this.redirect("/", http.StatusFound, w, r)
		} else {
			this.redirect("/login", http.StatusFound, w, r)
		}
	}
	this.render(w, nil, "auth.layout", "auth.navbar", "login")

}

func (this *Auth) Logout(w http.ResponseWriter, r *http.Request) {
	service.User.Logout(w, r)
	service.Session.Destroy()
	this.redirect("/", http.StatusFound, w, r)
}

func (this *Auth) Signup(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodPost {
		email := r.FormValue("email")
		name := r.FormValue("name")
		password := r.FormValue("password")

		if name != "" && password != "" && email != "" {
			if user := service.User.Create(email, name, password); user != nil {
				this.redirect("/", http.StatusFound, w, r)
				return
			}
		}

		this.redirect("/signup", http.StatusOK, w, r)
	}
	this.render(w, nil, "auth.layout", "navbar", "signup")
}
